var redis = require('redis');
var client = redis.createClient();

exports.cache = {
  load : function(key,cb){
    client.get(key,function(err,reply){
      if(err) return cb(err);
      try{
        if(!reply){
          return cb(null,null);
        }
        var obj = JSON.parse(reply);
        var expired_in = obj.expired_in;
        if(expired_in && expired_in < new Date().getTime() ){
          return cb(null,null);
        }
        return cb(null,obj.val);
      }catch(e){
        return cb("exception",null);
      }      
    });
  },
  save : function(key,val,timeout){
    var obj = {};
    obj.val = val;
    obj.expired_in = new Date().getTime() + timeout * 1000;
    client.set(key,JSON.stringify(obj));
  }
}